<template>
  <!--订单选择-->
  <a-modal
    title="选择投料单"
    :visible.sync="bottleShow"
    @ok="addPPRelationOk"
    :confirm-loading="confirmLoading"
    @cancel="handleCancel"
    width="80%"
    class="procedure-modal"
  >
    <div class="operation-search">
      <a-form layout="inline" :form="searchItem">
        <a-form-item label="计划生产日期：">
          <a-range-picker
            format="YYYY-MM-DD"
            :default-value="defaulttimeList"
            @change="onTime"
            v-model="defaulttimeList"
          >
            <template slot="dateRender" slot-scope="current">
              <div class="ant-calendar-date" :style="getcurrentStyle(current)">
                {{ current.date() }}
              </div>
            </template>
          </a-range-picker>
        </a-form-item>
        <a-form-item label="车间：">
          <a-select
            :allowClear="true"
            mode="multiple"
            :maxTagCount="1"
            class="selectwidth"
            v-model="searchItem.WSType"
            placeholder="请选择"
          >
            <a-select-option
              v-for="item in wSTypeList"
              :key="item.type"
              :value="item.type"
              >{{ item.name }}</a-select-option
            >
          </a-select>
        </a-form-item>
        <a-form-item label="投料单号：">
          <a-input
            :allowClear="true"
            placeholder="请输入"
            v-model="searchItem.planNo"
          />
        </a-form-item>
        <a-form-item label="产品编码：">
          <a-input
            :allowClear="true"
            placeholder="请输入"
            v-model="searchItem.MaterialCode"
          />
        </a-form-item>
        <a-form-item label="产品名称：">
          <a-input
            :allowClear="true"
            placeholder="请输入"
            v-model="searchItem.MaterialName"
          />
        </a-form-item>
        <a-form-item>
          <a-button class="default-button" @click="getPlansListFun">
            查询
          </a-button>
        </a-form-item>
        <a-form-item v-for="(group, index) in selectedGroups" :key="index">
          <span>{{ group.MaterialCode }}：</span>
          <span class="total-amount">需求数量 {{ group.ReqQty }}</span>
          <span class="total-amount">分配数量 {{ group.DistributeQty }} </span>
          <span
            class="total-amount"
            :class="{ negative: group.ReqQty - group.DistributeQty < 0 }"
          >
            剩余 {{ (group.ReqQty - group.DistributeQty).toFixed(3) }}
          </span>
        </a-form-item>
      </a-form>
    </div>
    <div>
      <div style="height: 500px">
        <a-table
          :columns="orderColums"
          :data-source="orderList"
          :row-key="(record) => record.num"
          :loading="loading1"
          :pagination="false"
          :scroll="{ x: 300, y: 450 }"
          size="middle"
        >
          <template slot="DistributeQty" slot-scope="text, record">
            <a-input-number
              id="inputNumber"
              :allowClear="true"
              :min="0"
              :max="record.ToDistributeQty"
              placeholder="请输入"
              v-model="record.DistributeQty"
              @change="updateSelectedTotalQty"
            />
          </template>
        </a-table>
      </div>
    </div>
  </a-modal>
</template>

<script>
import { debounce } from "@/common/debounce";
import {
  getPreparationPlanData,
  insSemiMGoodsPlanRelation,
} from "@/api/SemiMGoodsDistributeDetail/index";
import { GetWorkShopTypes } from "@/api/WorkShopType/index";
import { forEach } from "jszip";

export default {
  props: {
    bottleShow: {
      type: Boolean,
      default: false,
    },
    id: {
      type: String,
      default: "",
    },
    semiMGoodsDistributeDetailDtos: {
      type: Array,
      default: [],
    },
  },
  model: {
    prop: "bottleShow",
    event: "close",
  },

  data() {
    return {
      selectedGroups: [], // 新增分组数据
      confirmLoading: false, //modal的loading
      defaulttimeList: [], //默认时间
      expandedRowKeys: [],
      expandedRow: [],
      searchItem: {
        pageRequestModel: {
          pageIndex: 1,
          pageSize: 30,
        },
        materialNameCode: null,
        batchNo: null,
      }, //搜索参数
      orderColums: [
        {
          title: "序号",
          dataIndex: "num",
          fixed: "left",
          width: 50,
          align: "center",
        },
        {
          title: "销售单号",
          dataIndex: "SellOrderNo",
          sorter: true,
          align: "center",
          width: 120,
          customHeaderCell: () => ({
            style: { position: "relative" },
            on: {
              mousedown: (e) => this.handleResizeStart(e, 10),
            },
          }),
        },
        {
          title: "投料单号",
          dataIndex: "PlanNo",
          sorter: true,
          width: 120,
          align: "center",
          customHeaderCell: () => ({
            style: { position: "relative" },
            on: {
              mousedown: (e) => this.handleResizeStart(e, 20),
            },
          }),
        },
        {
          title: "生产批号",
          dataIndex: "BatchNo",
          align: "center",
          ellipsis: true,
          width: 150,
          customHeaderCell: () => ({
            style: { position: "relative" },
            on: {
              mousedown: (e) => this.handleResizeStart(e, 21),
            },
          }),
        },
        {
          title: "产品编码",
          dataIndex: "MaterialCode",
          align: "center",
          ellipsis: true,
          width: 100,
          customHeaderCell: () => ({
            style: { position: "relative" },
            on: {
              mousedown: (e) => this.handleResizeStart(e, 22),
            },
          }),
        },
        {
          title: "产品名称",
          dataIndex: "MaterialName",
          align: "center",
          ellipsis: true,
          width: 300,
          customHeaderCell: () => ({
            style: { position: "relative" },
            on: {
              mousedown: (e) => this.handleResizeStart(e, 23),
            },
          }),
        },
        {
          title: "计划生产日期",
          dataIndex: "PlanDt",
          align: "center",
          ellipsis: true,
          width: 100,
        },
        {
          title: "灌装单需求量",
          dataIndex: "ReqQty",
          align: "center",
          width: 100,
        },
        {
          title: "计划数量",
          dataIndex: "PlannedQuantity",
          align: "center",
          width: 100,
        },
        {
          title: "已分配数量",
          dataIndex: "AllocatedQty",
          align: "center",
          ellipsis: true,
          width: 100,
        },
        {
          title: "分配数量",
          key: "DistributeQty",
          scopedSlots: { customRender: "DistributeQty" },
          fixed: "right",
          width: 150,
        },
      ],
      wSTypeList: [],
      orderList: [], //工单选择列表
      orderItem: { batchNo: null },
      orderListTotal: 0,
      pageSizeOptions: ["30", "50", "100", "200", "500", "1000"], //分页
      loading1: false,
      planDicStatus: [
        {
          type: 0,
          name: "初始",
        },
        {
          type: 2,
          name: "已下发",
        },
        {
          type: 3,
          name: "开始生产",
        },
        {
          type: 5,
          name: "结束生产",
        },
      ],
      totalDistributeQty: 0, // 预分配总数
      remainingDistributeQty: 0, // 剩余分配数
      colResize: {
        isDragging: false,
        startX: 0,
        startWidth: 0,
        currentColIndex: -1,
      },
    };
  },
  methods: {
    //获取厂区列表
    async GetWorkShopTypesAllFun() {
      let that = this;

      let res = await GetWorkShopTypes({ segmentType: 0 });
      if (res.Status == 10000) {
        let wtList = [];
        res.Data.map((item) => {
          wtList.push({ type: item.WSType, name: item.WSName });
        });
        that.wSTypeList = wtList;
      } else {
        that.$message.error(res.Message);
      }
    },
    /** 修改投料单预分配 */
    async addPPRelationOk() {
      this.confirmLoading = true;
      try {
        this.essenceItem = this.orderList.filter(
          (item) => item.DistributeQty > 0
        );
        if (!this.essenceItem || this.essenceItem.length == 0) {
          this.$message.error("请输入分配数量");
        }

        this.essenceItem.forEach((item) => {
          item.SemiMGoodsDistributeID = this.id;
        });

        let res = await insSemiMGoodsPlanRelation(this.essenceItem);
        if (res.Status == 10000) {
          this.$message.success("添加成功");
          this.$emit("up-data");
          this.$emit("close", false);
        } else {
          this.$message.error(res.Message);
        }
      } catch (e) {
        this.$message.error(e);
      } finally {
        this.confirmLoading = false;
      }
    },
    //获取单据列表
    getPlansListFun: debounce(async function () {
      let that = this;
      that.loading1 = true;
      that.searchItem.semiMGoodsRecordDistributeID = this.id;
      let res = await getPreparationPlanData(that.searchItem);
      if (res.Status == 10000) {
        that.orderList = res.Data.PreparationPlanDtos;
        if (that.orderList) {
          that.orderList.map((item, index) => {
            item.num = index + 1;
            item.batchNo = item.BatchNo;
            item.PlanDt = that.dateExt.showDateTime(item.PlanDt);
          });
        }

        if (res.Data.SemiMGoodsDistributes) {
          that.selectedGroups = res.Data.SemiMGoodsDistributes;
        }
      } else {
        that.$message.error(res.Message);
      }
      that.loading1 = false;
    }),

    //关闭弹窗
    handleCancel() {
      this.orderItem = {};
      this.$emit("close", false);
    },
    //确认添加/修改
    handleOk() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
        }
      });
    },
    //时间选择
    onTime(e, e1) {
      let that = this;
      that.searchItem.StartDt = that.dateExt.showDate(e[0]._d);
      that.searchItem.EndDt = that.dateExt.showDate(e[1]._d);
    },

    //时间选择器的样式填充
    getcurrentStyle(current, today) {
      const style = {};
      if (current.date() === 1) {
        style.border = "1px solid #1890ff";
        style.borderRadius = "50%";
      }
      return style;
    },
    // 计算预分配总数和剩余分配数
    updateSelectedTotalQty() {
      // 按物料编码分组统计总分配量
      const distributeMap = this.orderList.reduce((acc, item) => {
        const key = item.MaterialCode;
        acc[key] = (acc[key] || 0) + Number(item.DistributeQty || 0);
        return acc;
      }, {});

      // 更新selectedGroups中的分配数量
      this.selectedGroups = this.selectedGroups.map((group) => ({
        ...group,
        DistributeQty: (
          distributeMap[group.MaterialCode] + group.AllocatedQty || 0
        ).toFixed(3),
      }));
    },
    // 修改重置方法
    resetSearch() {
      this.searchItem = {
        PlanNo: "",
        MaterialCode: "",
        MaterialName: "",
      };
      this.getPlansListFun();
    },
    handleResizeStart(e, colIndex) {
      e.preventDefault(); // 防止文本选择
      this.colResize = {
        isDragging: true,
        startX: e.clientX,
        startWidth: this.orderColums[colIndex].width,
        currentColIndex: colIndex,
      };
      document.addEventListener("mousemove", this.handleResizing);
      document.addEventListener("mouseup", this.handleResizeEnd);
    },

    handleResizing(e) {
      if (!this.colResize.isDragging) return;
      const delta = e.clientX - this.colResize.startX;
      const newWidth = Math.max(50, this.colResize.startWidth + delta);
      this.orderColums[this.colResize.currentColIndex].width = newWidth;
    },

    handleResizeEnd() {
      this.colResize.isDragging = false;
      this.colResize.currentColIndex = -1;
      document.removeEventListener("mousemove", this.handleResizing);
      document.removeEventListener("mouseup", this.handleResizeEnd);
    },
  },
  created() {
    let that = this;
  },
  watch: {
    bottleShow: {
      handler(newV, oldV) {
        if (newV) {
          this.expandedRowKeys = [];
          this.expandedRow = [];
          this.orderList = []; //工单选择列表
          this.orderItem = { batchNo: null };
          this.searchItem.StartDt = this.dateExt.getDay(-30);
          this.defaulttimeList[0] = this.searchItem.StartDt;
          this.searchItem.EndDt = this.dateExt.getDay(30);
          this.defaulttimeList[1] = this.searchItem.EndDt;
          this.GetWorkShopTypesAllFun();
          this.getPlansListFun();
        }
      },
      immediate: true, // 重点
      deep: true, // 重点
    },
  },
};
</script>

<style lang="less" scoped>
.procedure-modal {
  .title {
    border-bottom: 1px solid #eeeeee;
    padding: 0.625rem 0;
    margin-bottom: 0.625rem;
  }
  .production-reporting {
    border-bottom: 1px solid #eeeeee;
    padding: 0.625rem 0;
    height: 1000px;
    margin-bottom: 0.625rem;
    .name {
      font-size: 1.125rem;
      font-weight: bold;
    }
  }
  .table-box {
    display: flex;
    justify-content: space-evenly;
    align-items: center;
    .left {
      flex: 1;
    }
    .right {
      flex: 1;
    }
    .center {
      display: flex;
      flex-direction: column;
      margin: 0 1.25rem;
    }
    .search {
      margin: 0.625rem 0;
    }
    .name {
      font-size: 1.125rem;
      font-weight: bold;
    }
  }
  .searchrow {
    display: flex;
    justify-content: flex-end;
    padding: 2px;
  }
  .operation-search {
    display: flex;
    //justify-content: flex-end;
    border-bottom: 2px solid #f0f2f5;
    //margin-bottom: 0.9375rem;
    .selectwidth {
      width: 15rem;
    }
    .selectrightwidth {
      width: 7rem;
    }
  }
}
/deep/.ant-table-body {
  &::-webkit-scrollbar {
    margin: 0.2rem;
    //整体样式
    height: 0.4125rem;
    width: 0.3rem;
  }

  &::-webkit-scrollbar-thumb {
    //滑动滑块条样式
    border-radius: 0.625rem;
    -webkit-box-shadow: inset 0 0 1px rgba(0, 0, 0, 0.2);
    background: #009a9a;
    // background: rgba(2, 35, 60, 1);
  }

  &::-webkit-scrollbar-track {
    //轨道的样式
    -webkit-box-shadow: 0;
    border-radius: 0.625rem;
    background: #ccc;
  }

  &::-webkit-scrollbar-corner {
    background: red;
  }
}
.total-amount {
  display: inline-flex;
  align-items: center;
  padding: 4px 12px;
  background: #fafafa;
  border: 1px solid #f0f0f0;
  border-radius: 4px;
  margin: 8px;

  font-size: 14px;
  color: #1890ff;
  font-weight: 500;
  min-width: 80px;
  justify-content: center;

  &.negative {
    color: #ff4d4f;
  }
}
::v-deep .ant-table-thead > tr > th {
  position: relative;
  user-select: none;

  &::after {
    content: "";
    position: absolute;
    right: -3px !important;
    top: 0;
    z-index: 1;
    width: 5px;
    height: 100%;
    cursor: col-resize;
    background-color: transparent;
    transition: background-color 0.3s;
  }

  &:hover::after {
    background-color: #1890ff;
  }
}

.ant-table-cell {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
